package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constants.admin.AdminConstants;
import com.heima.common.exception.CustException;
import com.heima.feigns.article.ArticleFeign;
import com.heima.feigns.wemedia.WemediaFeign;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.media.pojos.WmUser;
import com.heima.model.user.dtos.AuthDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.user.pojos.ApUserRealname;
import com.heima.user.mapper.ApUserRealnameMapper;
import com.heima.user.service.ApUserRealnameService;
import com.heima.user.service.ApUserService;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;


@Service
public class ApUserRealnameServiceImpl extends ServiceImpl<ApUserRealnameMapper, ApUserRealname> implements ApUserRealnameService {

    @Resource
    private ApUserService apUserService;

    @Resource
    private WemediaFeign wemediaFeign;

    @Resource
    private ArticleFeign articleFeign;

    @Override
    public ResponseResult loadListByStatus(AuthDto dto) {
        //检查参数
        if (dto == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //创建查询条件
        dto.checkParam();
        Page<ApUserRealname> realnamePage = new Page<>(dto.getPage(), dto.getSize());
        LambdaQueryWrapper<ApUserRealname> lambdaQueryWrapper = Wrappers.lambdaQuery();
        //判断是否有条件
        if (dto.getStatus() != null) {
            lambdaQueryWrapper.eq(ApUserRealname::getStatus, dto.getStatus());
        }
        IPage<ApUserRealname> page = page(realnamePage, lambdaQueryWrapper);
        PageResponseResult pageResponseResult = new PageResponseResult(dto.getPage(), dto.getSize(), (int) page.getTotal());
        pageResponseResult.setData(page.getRecords());
        //返回结果
        return pageResponseResult;
    }

    @Override
    @Transactional
    @GlobalTransactional(rollbackFor = {Exception.class})
    public ResponseResult updateStatusById(AuthDto dto, Short status) {
        //检查参数
        if (dto == null||dto.getId()==null) {
            CustException.cust(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //判断对应id用户是否存在
        ApUserRealname apUserRealname = getById(dto.getId());
        if(apUserRealname==null){
            CustException.cust(AppHttpCodeEnum.AP_USER_REALNAME_ERROR);
        }
        //判断用户真实信息是否存在
        ApUser apUser = apUserService.getOne(Wrappers.<ApUser>lambdaQuery().eq(ApUser::getId,apUserRealname.getUserId()));
        if (apUser == null) {
            CustException.cust(AppHttpCodeEnum.AP_USER_REALNAME_NOT_EXIST);
        }
        //判断用户真实信息的审核状态是否是待审核
        if (apUserRealname.getStatus() != AdminConstants.WAIT_AUTH) {
            CustException.cust(AppHttpCodeEnum.AP_USER_REALNAME_ERROR);
        }
        //判断是否审核拒绝
        if(status==AdminConstants.FAIL_AUTH){
            if(dto.getMsg()!=null){
                apUserRealname.setReason(dto.getMsg());
            }
            //修改用户真实信息审核状态
            authPass(apUserRealname,status);
            return ResponseResult.okResult();
        }
        //判断是否是审核通过
        if(status!=AdminConstants.PASS_AUTH){
            CustException.cust(AppHttpCodeEnum.IDNO_FAIL);
        }
        authPass(apUserRealname,status);
        //添加自媒体用户
        WmUser wmUser = createWmUser(apUser);
        if (wmUser==null){
            CustException.cust(AppHttpCodeEnum.CREATE_MEDIA_FAIL);
        }
        //添加文章作者用户
        ResponseResult responseResult = createAuthUser(wmUser);
        //判断是否成功
        if(responseResult.getCode()!=0){
            CustException.cust(AppHttpCodeEnum.ADD_AUTH_USER_ERROR);
        }
        //修改用户身份
        apUser.setFlag((short)1);
        apUser.setIdentityAuthentication(true);
        boolean flag = apUserService.updateById(apUser);
        if(flag==false){
            CustException.cust(AppHttpCodeEnum.UPDATE_AP_USER_FAIL);
        }
        //判断实名认证身份证与姓名是否匹配正确
//        boolean flag = IdCardUtils.checkIdCardInfo(apUserRealname.getName(), String.valueOf(apUserRealname.getIdno()));
//        if(flag==false){
//            CustException.cust(AppHttpCodeEnum.IDNO_FAIL);
//        }
        //返回响应
        //测试异常
//        int i=1/0;
        return ResponseResult.okResult();
    }

    private ResponseResult createAuthUser(WmUser wmUser) {
        ApAuthor byUserId = articleFeign.findByUserId(wmUser.getApUserId());
        if(byUserId!=null){
            CustException.cust(AppHttpCodeEnum.AUTH_USER_IS_EXIST);
        }
        ApAuthor apAuthor = new ApAuthor();
        apAuthor.setName(wmUser.getName());
        apAuthor.setType(AdminConstants.AUTHOR_TYPE);
        apAuthor.setUserId(wmUser.getApUserId());
        apAuthor.setCreatedTime(new Date());
        apAuthor.setWmUserId(wmUser.getId());
        return articleFeign.save(apAuthor);
    }

    private WmUser createWmUser(ApUser apUser) {
        //判断自媒体账户是否存在
        WmUser byName = wemediaFeign.findByName(apUser.getName());
        if(byName!=null){
            CustException.cust(AppHttpCodeEnum.MEDIA_USER_IS_EXIST);
        }
        WmUser wmUser = new WmUser();
        wmUser.setApUserId(apUser.getId());
        wmUser.setName(apUser.getName());
        wmUser.setPassword(apUser.getPassword());
        wmUser.setSalt(apUser.getSalt());
        wmUser.setImage(apUser.getImage());
        wmUser.setPhone(apUser.getPhone());
        wmUser.setType(0);
        wmUser.setStatus(9);
        wmUser.setCreatedTime(new Date());
        return wemediaFeign.save(wmUser);
    }

    //修改用户真实信息的审核状态
    private void authPass(ApUserRealname apUserRealname, Short status) {
        apUserRealname.setStatus(status);
        updateById(apUserRealname);
    }
}
